package com.yf.htmlsourceview;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//import android.os.StrictMode;

public class MainActivity extends Activity {

	private TextView tv_content;
	@SuppressLint("HandlerLeak")
	// 主线程创建一个消息监听处理器
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// 2.在主线程更新UI
			tv_content.setText((String) msg.obj);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 系统版本android4.0以上只要是写在主线程（就是Activity）中的HTTP请求，运行时都会报错。
		// 这是因为Android在4.0以后为了防止应用的ANR（Aplication Not Response）异常，
		// Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。
		// 避免ANR第一种方法：

		// if (android.os.Build.VERSION.SDK_INT > 9) {
		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder().permitAll()
		// .build();
		// StrictMode.setThreadPolicy(policy);
		// }

		final EditText et_url = (EditText) findViewById(R.id.et_url);
		tv_content = (TextView) findViewById(R.id.tv_content);
		Button btn_show = (Button) findViewById(R.id.btn_show);

		btn_show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 避免ANR第二种方法：
				// 1.联网在子线程操作
				new Thread() {
					public void run() {
						String urlString = et_url.getText().toString().trim();
						try {
							URL url = new URL(urlString);
							Thread thread = new Thread();
							thread.start();
							HttpURLConnection connection = (HttpURLConnection) url.openConnection();
							connection.setRequestMethod("GET");
							connection.setConnectTimeout(10000);
							int resCode = connection.getResponseCode();

							if (resCode == 200) {
								InputStream is = connection.getInputStream();
								String content = StringUtil.fromStream(is);

								Message msg = new Message();
								msg.obj = content;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							e.printStackTrace();
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									Toast.makeText(MainActivity.this, "网络连接异常", Toast.LENGTH_SHORT)
											.show();
								}

							});
						}
					};
				}.start();
			}
		});

	}

}
